package com.vnp.vchat.version2;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.vnp.vchat.MainPanelActivity;
import com.vnp.vchat.R;
import com.vnp.vchat.UIControls.MyCircleImageView;
import com.vnp.vchat.Util.Common;
import com.vnp.vchat.Util.DecodeUtils;
import com.vnp.vchat.Util.KeyboardHelper;
import com.vnp.vchat.Util.PreferenceHelper;
import com.vnp.vchat.Util.Utils;
import com.vnp.vchat.database.MySQLiteHelper;
import com.vnp.vchat.httpclient.HttpClientHelper;
import com.vnp.vchat.httpclient.MyJsonHttpResponseHandler;

public class CapNhatThongTinActivity extends Activity implements OnClickListener{

	TextView title;
	
	Button btnTieptuc;	
	ImageButton btnBack;
	
	TextView titleTen, titleEmail, titleMK;
	EditText edtTen, edtEmail, edtMK;
	
	LinearLayout edtMain;
	MyCircleImageView imgAvatar;
	
	// show dialog chon anh
	Dialog dChoose;
	
	String TEMP_TAKE_IMAGE = Common.SDCARD_IMAGE + "tmp_avatar_photo.jpg";
	String file_path;
	
	// chon anh
	private static final int PICK_PHOTO = 100;
	private static final int CAPTURE_PHOTO = 200;
	
	Uri mCapturedImageURI;
	String selectedPath;
	Uri selectedImageUri;
	
	byte[] byteArray;
	
	String accID;
	ProgressBar progressBar;
	
	PreferenceHelper preferenceHelper;
	String phone;
	
	Dialog dS;
	ProgressDialog progressDialog = null;
	ArrayList<String> list = new ArrayList<String>();
	MySQLiteHelper db;
	
	Runnable r = new Runnable() {
		
		@Override
		public void run() {
			gotoMain();
		}
	};
	
	Handler mHandler = new Handler();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cap_nhat_thong_tin);
		
		edtMain = (LinearLayout) findViewById(R.id.edt_main);
		
		accID = getIntent().getStringExtra("acc_id");
		
		phone = getIntent().getStringExtra("phone");
		
		preferenceHelper = new PreferenceHelper(this);
		
		db = new MySQLiteHelper(this);
		
		title = (TextView) findViewById(R.id.title);
		btnBack = (ImageButton) findViewById(R.id.btn_function1);
		btnBack.setVisibility(View.VISIBLE);
		progressBar = (ProgressBar) findViewById(R.id.progressBar1);
		titleTen = (TextView) findViewById(R.id.txt_ten);
		titleEmail = (TextView) findViewById(R.id.txt_email);
		titleMK = (TextView) findViewById(R.id.txt_matkhau);
		
		edtTen = (EditText) findViewById(R.id.edt_ten);
		edtEmail = (EditText) findViewById(R.id.edt_email);
		edtMK = (EditText) findViewById(R.id.edt_matkhau);
		
		btnTieptuc = (Button) findViewById(R.id.btn_hoanthanh);
		imgAvatar = (MyCircleImageView) findViewById(R.id.img_avatar);
		
		KeyboardHelper.setupUI(CapNhatThongTinActivity.this, edtMain);
		
		init();
		
		setFont();
	}
	
	void init(){
		title.setText("Cập nhật thông tin");
		btnBack.setOnClickListener(this);
		btnTieptuc.setOnClickListener(this);
		imgAvatar.setOnClickListener(this);
	}
	
	void setFont(){
		title.setTypeface(Utils.getTypefaceBold(CapNhatThongTinActivity.this));
		titleTen.setTypeface(Utils.getTypefaceMedium(CapNhatThongTinActivity.this));
		titleEmail.setTypeface(Utils.getTypefaceMedium(CapNhatThongTinActivity.this));
		titleMK.setTypeface(Utils.getTypefaceMedium(CapNhatThongTinActivity.this));
		
		edtTen.setTypeface(Utils.getTypefaceLight(CapNhatThongTinActivity.this));
		edtEmail.setTypeface(Utils.getTypefaceLight(CapNhatThongTinActivity.this));
		edtMK.setTypeface(Utils.getTypefaceLight(CapNhatThongTinActivity.this));
		btnTieptuc.setTypeface(Utils.getTypefaceBold(CapNhatThongTinActivity.this));
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_function1:
			closeActivity();
			break;
		case R.id.btn_hoanthanh:
			/*if (byteArrayCheck3b(byteArray) == false){
				Toast.makeText(CapNhatThongTinActivity.this, "Bạn chưa chọn avatar!", Toast.LENGTH_SHORT).show();
			} else {
				
			}*/
			
			uploadImage();
			break;
		case R.id.img_avatar:
			showDialogChonanh();
			break;
		case R.id.btn_choose_image:
			dChoose.dismiss();
			openGallery();
			break;
		case R.id.btn_capture_image:
			dChoose.dismiss();
			takeImage();
			break;
		case R.id.btn_thoat:
			dChoose.dismiss();
			break;
			
		case R.id.btn_thoat_tk:
			dS.dismiss();
			showProgressDialog();
			UpdateContactAsyn asyn = new UpdateContactAsyn();
			asyn.execute("");
			break;
		case R.id.btn_ko:
			dS.dismiss();
			mHandler.removeCallbacks(r);
			mHandler.postDelayed(r, 300);
			break;
			
			
		default:
			break;
		}
	}
	
	@Override
	public void onBackPressed() {
		closeActivity();
	}
	
	void closeActivity(){
		finish();
		overridePendingTransition(R.anim.over_main_right, R.anim.trans_right_out);
	}
	
	// show dialog sau khi them thanh cong
	public void showDialogChonanh() {
		dChoose = new Dialog(this, R.style.DialogSlideAnim);
		dChoose.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dChoose.setContentView(R.layout.dialog_choose_photo);

		Button btnChonanh = (Button) dChoose
				.findViewById(R.id.btn_choose_image);
		Button btnChupanh = (Button) dChoose
				.findViewById(R.id.btn_capture_image);

		Button btnThoat = (Button) dChoose.findViewById(R.id.btn_thoat);
		
		btnChonanh.setTypeface(Utils.getTypefaceMedium(CapNhatThongTinActivity.this));
		btnChupanh.setTypeface(Utils.getTypefaceMedium(CapNhatThongTinActivity.this));
//				btnThoat.setTypeface(Utils.getTypefaceBold(ChatActivity.this), Typeface.BOLD);
		
		dChoose.show();
		dChoose.getWindow().setBackgroundDrawable(new ColorDrawable(0));
		dChoose.setCanceledOnTouchOutside(true);
		dChoose.getWindow().setGravity(Gravity.BOTTOM);
		dChoose.show();

		// setonclick
		btnChonanh.setOnClickListener(this);
		btnChupanh.setOnClickListener(this);
		btnThoat.setOnClickListener(this);
	}
			
	// chon anh
	public void openGallery() {
		File ff = new File(TEMP_TAKE_IMAGE);
		if (ff.exists())
			ff.delete();
		Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
		photoPickerIntent.setType("image/*");
		startActivityForResult(photoPickerIntent, PICK_PHOTO);
	}
	
	// chup anh
	public void takeImage() {
		String fileName = "temp.jpg";
		ContentValues values = new ContentValues();
		values.put(MediaStore.Images.Media.TITLE, fileName);
		mCapturedImageURI = getContentResolver().insert(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
		startActivityForResult(intent, CAPTURE_PHOTO);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case PICK_PHOTO:
				Uri u = (Uri) data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };
				Cursor cursor = getContentResolver().query(u, filePathColumn,
						null, null, null);
				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				file_path = cursor.getString(columnIndex);

				Log.i("DATA", "File upload :" + file_path);
				
				
				
				Bitmap bm = DecodeUtils.decode(CapNhatThongTinActivity.this,
						Uri.parse(file_path), 800, 800);
				
//				Log.i("vChat", "Width: "+bm.getWidth() + "Height: "+bm.getHeight());
				
				if (bm == null) {
					Toast.makeText(CapNhatThongTinActivity.this,
							"Bạn chưa chọn ảnh!", Toast.LENGTH_SHORT).show();
					return;
				}
				
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				bm.compress(Bitmap.CompressFormat.JPEG, 75, stream);
				byteArray = stream.toByteArray();

				imgAvatar.setImageBitmap(bm);
				
				// upload image
//				uploadImage();
				try {
					if (cursor != null){
						cursor.close();	
					}
				} catch (IllegalStateException e) {
					e.printStackTrace();
				}

				break;
			case CAPTURE_PHOTO:
				String[] projection = { MediaStore.Images.Media.DATA };
				Cursor cursor1 = managedQuery(mCapturedImageURI, projection,
						null, null, null);
				int column_index_data = cursor1
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor1.moveToFirst();
				file_path = cursor1.getString(column_index_data);
				Log.i("DATA", "File upload :" + file_path);

				Bitmap bm1 = DecodeUtils.decode(CapNhatThongTinActivity.this,
						Uri.parse(file_path), 800, 800);
				if (bm1 == null) {
					Toast.makeText(CapNhatThongTinActivity.this,
							"Bạn chưa chọn ảnh!", Toast.LENGTH_SHORT).show();
					return;
				}
				
				ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
				bm1.compress(Bitmap.CompressFormat.JPEG, 75, stream1);
				byteArray = stream1.toByteArray();
				
				imgAvatar.setImageBitmap(bm1);
				
//				imgTungbuoc.setScaleType(ScaleType.CENTER_CROP);
//				imgTungbuoc.setImageBitmap(bm1);

//				uploadImage();
				try {
					if (cursor1 != null){
						cursor1.close();
					} 
				} catch (IllegalStateException e) {
					e.printStackTrace();
				}
				break;
			}
		}
	}
	
	
	@Override
	@Deprecated
	public void startManagingCursor(Cursor c) {
		if (Build.VERSION.SDK_INT < VERSION_CODES.HONEYCOMB) {
	        super.startManagingCursor(c);
	    }
	}
	
	void uploadImage() {
		
		progressBar.setVisibility(View.VISIBLE);
		btnTieptuc.setText("Đang cập nhật...");
		
		RequestParams params = new RequestParams();
		params.put("acc_id", accID);
		params.put("full_name", edtTen.getText().toString());
		params.put("email", edtEmail.getText().toString());
		params.put("password", edtMK.getText().toString());
		
		params.put("avatar", new ByteArrayInputStream(byteArray), "image.jpg");

		AsyncHttpClient client = new AsyncHttpClient();
		
		String credentials = "vchat-mobile" + ":" + "I2o5VG0c5a5dnZ866Y8Sguthojavuw";  
		String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); 
		client.addHeader("Authorization", "Basic " + base64EncodedCredentials);
		
		client.post("https://id.vatgia.com/api/v1/account/updateInfo", params,
				new MyJsonHttpResponseHandler() {

					@SuppressLint("NewApi")
					@Override
					public void onFailure(int statusCode, Throwable error) {
						progressBar.setVisibility(View.GONE);
						btnTieptuc.setText("Cập nhật");
						
						String e = null;
						try {
							e = new String(error.getMessage().toString().getBytes("UTF-8"));
						} catch (UnsupportedEncodingException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
						
						if (statusCode == 400){
							Log.i("ERROR", ""+error+ " Status : "+statusCode);
							Toast.makeText(CapNhatThongTinActivity.this, e , Toast.LENGTH_SHORT).show();
						}else if (statusCode == 403) {
							Log.i("ERROR", ""+error+ " Status : "+statusCode);
							Toast.makeText(CapNhatThongTinActivity.this, e, Toast.LENGTH_SHORT).show();
//							login(edtEmail.getText().toString());
						}else if (statusCode == 404) {
							Log.i("ERROR", ""+error+ " Status : "+statusCode);
							Toast.makeText(CapNhatThongTinActivity.this, e, Toast.LENGTH_SHORT).show();
						}else if (statusCode == 406) {
							Log.i("ERROR", ""+error+ " Status : "+statusCode);
							Toast.makeText(CapNhatThongTinActivity.this, e, Toast.LENGTH_SHORT).show();
						}
					}

					@Override
					public void onSuccess(int statusCode, JSONObject re) {
						btnTieptuc.setText("Cập nhật");
						if (statusCode == 200){
							/*preferenceHelper.setUserName(edtTen.getText().toString());
//			            	preferenceHelper.setMyAvatar();
			            	preferenceHelper.setEmail(edtEmail.getText().toString());*/
							login(phone);
							Log.i("DATA", "Thong tin cap nhat: "+re.toString());
						}
					}

					/*@Override
					public void onFailure(Throwable error) {
						super.onFailure(error);
						progressBar.setVisibility(View.GONE);
						Toast.makeText(CapNhatThongTinActivity.this,
								"Request failed.", Toast.LENGTH_SHORT).show();
					}

					@Override
					public void onSuccess(JSONObject re) {
						progressBar.setVisibility(View.GONE);
						try {
							String error = re.getString("error");
							
							if (!error.equals("")){
								Log.i("DATA", "File qua lon");
								
								Toast.makeText(CapNhatThongTinActivity.this, "File ảnh quá lớn.", Toast.LENGTH_SHORT).show();
							} else {
								String data = re.getString("data");
								Log.i("DATA", "URL tra ve: "+data);
								gotoMain();
							}
							
						} catch (JSONException e) {
							e.printStackTrace();
						}

					}*/
			
				
			
				});
	}
	
	void gotoMain(){
		Intent t = new Intent(CapNhatThongTinActivity.this, MainPanelActivity.class);
		finish();
		Intent broadcastIntent = new Intent();
		broadcastIntent.setAction("HUY");
		sendBroadcast(broadcastIntent);
		startActivity(t);
		overridePendingTransition(R.anim.trans_left_in, R.anim.over_main_left);
	}
	
	private boolean byteArrayCheck3b(byte[] array) {
	    int hits = 0;
	    for (byte b : array) {
	        if (b != 0) {
	            hits++;
	        }
	    }
	    return (hits == 0);
	}
	
	void login(String tk){
		
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
				Toast.makeText(CapNhatThongTinActivity.this, "Đăng nhập thất bại.", Toast.LENGTH_SHORT).show();
			}
			
			

			@Override
			@Deprecated
			public void onFailure(Throwable error, String content) {
				Toast.makeText(CapNhatThongTinActivity.this, "Đăng nhập thất bại.", Toast.LENGTH_SHORT).show();
			}



			@Override
			public void onSuccess(JSONObject re) {
				progressBar.setVisibility(View.GONE);
				Log.i("LOGIN", ""+re.toString());
				try {
					int status = re.getInt("status");
					if (status == 1){
		            	
		            	JSONObject uinf = re.getJSONObject("uinfo");
		            	JSONObject settings = re.getJSONObject("setting");
		            	
		            	preferenceHelper.setUserId(uinf.getString("use_sso_id"));
		            	preferenceHelper.setHash(re.getString("hash"));
		            	preferenceHelper.setHashSetting(re.getString("hash_setting"));
		            	preferenceHelper.setDomainConnect(re.getString("domain_connect"));
		            	preferenceHelper.setPostConnect(re.getString("port_connect"));
		            	preferenceHelper.setDataJoin(re.getString("datajoin"));
		            	preferenceHelper.setSettingNotifi(settings.getString("notifi"));
		            	preferenceHelper.setSettingFeed(settings.getString("feed"));
		            	preferenceHelper.setSettingDisplay(settings.getString("showmsg"));
		            	preferenceHelper.setUserName(uinf.getString("name"));
		            	preferenceHelper.setMyAvatar(uinf.getString("imaege"));
		            	preferenceHelper.setEmail(uinf.getString("email"));
		            	preferenceHelper.setAdminId(re.getString("admin_id"));
//		            	preferenceHelper.setPhone(value)
//		            	gotoMain();
		            	
		            	runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								showDialogCapnhatDanhba();
							}
						});
		            	
		            	
		            } else if (status == 0) {
		            	progressBar.setVisibility(View.GONE);
		            	btnTieptuc.setText("Tiếp tục");
						btnTieptuc.setClickable(true);
						Toast.makeText(CapNhatThongTinActivity.this, "Đăng nhập thất bại.", Toast.LENGTH_SHORT).show();
		            }
					
				} catch (JSONException e) {
					e.printStackTrace();
					progressBar.setVisibility(View.GONE);
	            	btnTieptuc.setText("Tiếp tục");
					btnTieptuc.setClickable(true);
					Toast.makeText(CapNhatThongTinActivity.this, "Đăng nhập thất bại.", Toast.LENGTH_SHORT).show();
				}
			}
		});
		
		String hash = Utils.MD5(""+Common.KEY_HTTP+"|"+""+tk+"|"+""+edtMK.getText().toString());
		
		Log.i("LOGIN", "HASH: "+hash);
		
		httpClientHelper.loginByPhoneOrEmail(tk, edtMK.getText().toString(), hash, Common.KEY_HTTP);
	}
	
	void showDialogCapnhatDanhba(){
		dS = new Dialog(this);
		dS.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dS.setContentView(R.layout.dialog_thoat_tk);
		
		
		TextView txtThoat = (TextView) dS.findViewById(R.id.str_canhbao_thoat);
		
		txtThoat.setText("Bạn có muốn đồng bộ danh bạ của bạn với vChat không?");
		
		Button btnThoat = (Button) dS.findViewById(R.id.btn_thoat_tk);
		Button btnKo = (Button) dS.findViewById(R.id.btn_ko);
		dS.show();
		dS.getWindow().setBackgroundDrawable(new ColorDrawable(0));
		dS.setCanceledOnTouchOutside(true);
		dS.getWindow().setGravity(Gravity.CENTER);
		dS.show();
		
		txtThoat.setTypeface(Utils.getTypefaceRegular(CapNhatThongTinActivity.this));
		btnThoat.setTypeface(Utils.getTypefaceRegular(CapNhatThongTinActivity.this));
		btnKo.setTypeface(Utils.getTypefaceRegular(CapNhatThongTinActivity.this));
		// setonclick
		btnThoat.setOnClickListener(this);
		btnKo.setOnClickListener(this);
	}
	
	private class UpdateContactAsyn extends AsyncTask<String, String, String>{

		@Override
		protected String doInBackground(String... params) {
			Utils.getContact(CapNhatThongTinActivity.this);
			sendContactHttp();
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) {
			progressDialog.dismiss();
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					Toast.makeText(CapNhatThongTinActivity.this, "Cập nhật thành công", Toast.LENGTH_SHORT).show();
					gotoMain();
				}
			});
		}
	}
	
	void sendContactHttp(){
		
		
		list = db.getPhoneFromDB();
		
		JSONArray jsonArray = new JSONArray(list);
		
		/*for (int i = 0; i < objContacts.size(); i++) {
			jsonArray.put(objContacts.get(i).getJSONObject());
		}*/
		
		
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				Log.i("DATA", "Cap nhat danh ba loi");
			}

			@Override
			public void onSuccess(JSONObject re) {
				Log.i("DATA", "Cap nhat danh ba thanh cong :"+re.toString());
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						Toast.makeText(CapNhatThongTinActivity.this, "Cập nhật thành công", Toast.LENGTH_SHORT).show();
					}
				});
				
				gotoMain();
			}
			
		});
		
		
		httpClientHelper.sendContact(preferenceHelper.getAdminId(), jsonArray, preferenceHelper.getHashSetting());
	}
	
	void showProgressDialog(){
		 progressDialog = new ProgressDialog(this);
	     progressDialog.show();        
	     progressDialog.setContentView(R.layout.custom_progress_dialog);
	     //se ppdrá cerrar simplemente pulsando back
	     progressDialog.setCancelable(false);
	     
	     new Handler().postDelayed(new Runnable() {
	         public void run() {                
	             progressDialog.dismiss();         
	         }
	     }, 90000); 
	}
	
	
}
